package com.baobao.druid.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author baobao
 * @create 2020-09-09 10:52
 * @description
 */
@Configuration
// 指定关联数据源ds2的mapper接口扫描包，以及所使用的SqlSessionTemplate
@MapperScan(basePackages = "com.baobao.druid.mapper.ds2",sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DS2Config {
    // 注入数据源ds2
    @Bean(name = "dataSource2")
    @ConfigurationProperties("spring.datasource.druid.ds2")
    public DataSource dataSourceTwo(){
        return DruidDataSourceBuilder.create().build();
    }

    // 创建与ds2关联的SqlSessionFactory
    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // 注入指定的ds2数据源
        bean.setDataSource(dataSource);
        // 如果mapper用xml配置，还需要指定对应的mapper.xml的位置
        //  bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/db2/*.xml"));
        return bean.getObject();
    }

    // 配置ds2相关的事务管理
    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("dataSource2") DataSource dataSource) {
        // 利用指定的ds2数据源创建事务管理器
        return new DataSourceTransactionManager(dataSource);
    }

    // 配置ds2相关的SqlSessionTemplate
    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        // 利用指定的ds2数据源创建SqlSessionTemplate
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
